/*
 * SyncResource.java
 *
 * Created on April 12, 2007, 1:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app.admin;

import java.util.Date;
import java.util.logging.Level;
import org.atomojo.app.App;
import org.atomojo.app.Storage;
import org.atomojo.app.auth.User;
import org.atomojo.app.db.DB;
import org.atomojo.app.db.SyncProcess;
import org.atomojo.app.sync.PullSynchronizer;
import org.atomojo.app.sync.PushSynchronizer;
import org.atomojo.app.sync.SyncException;
import org.atomojo.app.sync.Synchronizer;
import org.atomojo.app.sync.TargetNotAvailableException;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class SyncProcessStartResource extends ServerResource
{
   
   /** Creates a new instance of SyncResource */
   public SyncProcessStartResource() {
      setNegotiated(false);
   }
   
   public Representation get()
   {
      final DB db = (DB)getRequest().getAttributes().get(App.DB_ATTR);
      final Storage storage = (Storage)getRequest().getAttributes().get(App.STORAGE_ATTR);
      final String name = getRequest().getAttributes().get("name").toString();

      SyncProcess proc = db.getSyncProcess(name);
      
      if (proc!=null) {
         Synchronizer sync = null;
         if (proc.isPullSynchronization()) {
            User user = (User)getRequest().getAttributes().get(App.USER_ATTR);
            sync = new PullSynchronizer(getContext().getLogger(),getApplication().getMetadataService(),user,db,storage,proc);
            ((PullSynchronizer)sync).setAdditive(proc.isAdditive());
         } else {
            sync = new PushSynchronizer(getContext().getLogger(),db,storage,proc);
         }
         try {
            sync.setSynchronizationAt(new Date());
            sync.sync();
            if (sync.getErrorCount()>0) {
               getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
               return new StringRepresentation("There were "+sync.getErrorCount()+" synchronization errors.  See the log for details.");
            } else {
               getResponse().setStatus(Status.SUCCESS_OK);
               return null;
            }
         } catch (TargetNotAvailableException ex) {
            getResponse().setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
            return new StringRepresentation("The target service is not available.");
         } catch (SyncException ex) {
            getLogger().log(Level.SEVERE,"Synchronization of target failed.",ex);
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            return new StringRepresentation(ex.getMessage());
         }
      } else {
         getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
         return null;
      }
   }
   
}
